package com.lzy.managersystem.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzy.managersystem.controller.dto.UserDTO;
import com.lzy.managersystem.pojo.User;
import com.lzy.managersystem.service.IUserService;
import com.lzy.managersystem.service.UserService;
import com.lzy.managersystem.tools.Constans;
import com.lzy.managersystem.tools.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private IUserService iUserService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/")
    public Result selectAll() {
        //1.从缓存中获取数据
        String jsonUser = stringRedisTemplate.opsForValue().get(Constans.USER_KEY);
        List<User> list;
        if (StrUtil.isBlank(jsonUser)) {  //2.jsonUser为空
            //3.从数据库获取数据
            list = userService.getAllUser();
            //4.保存到redis缓存中
            stringRedisTemplate.opsForValue().set(Constans.USER_KEY, JSONUtil.toJsonStr(list));
        } else {
            //减轻数据库压力
            //5.如果有，从redis缓存中取数据
            list = JSONUtil.toBean(jsonUser, new TypeReference<List<User>>() {
            }, true);//忽略转换json数据的错误

        }


        return Result.success(list);
    }

    @PostMapping("/inster")
    public Result insertUser(@RequestBody User user){
        System.out.println(user);
       int flag= userService.insterUser(user);
        return Result.success(flag);
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id){
       int flag= userService.deleteUser(id);
        return Result.success(flag);
    }

    @PostMapping("/del/batch")
    public Result deleteBatchUser(@RequestBody List<Integer> ids){
       int flag= userService.deleteBatchUser(ids);
        return Result.success(flag);
    }

    @PutMapping("/")
    public Result UpdataUser(@RequestBody User user){
        int flag = userService.updateUser(user);
        flushredis(Constans.USER_PERSON);
        return Result.success(flag);
    }

    //查询所有用户（分页）
    @GetMapping("/page")
    public Result selectUserPage(@RequestParam Integer pageSize,
                                      @RequestParam Integer pageNum,
                                      @RequestParam(defaultValue = "") String username,
                                      @RequestParam(defaultValue = "") String email,
                                      @RequestParam(defaultValue = "") String address){
        IPage<User> userIPage = new Page<>(pageNum,pageSize);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if (!"".equals(username)) {
            userQueryWrapper.like("username", username);
        }
        if (!"".equals(email)) {
            userQueryWrapper.like("email", email);
        }
        if (!"".equals(address)) {
            userQueryWrapper.like("address", address);
        }
//        IPage<User> page;
//        String jsonUserPage =stringRedisTemplate.opsForValue().get(Constans.USER_KEY);
//        if(StrUtil.isBlank(jsonUserPage)){
//            page = userService.page(userIPage, userQueryWrapper);
//            stringRedisTemplate.opsForValue().set(Constans.USER_KEY, JSONUtil.toJsonStr(page));
//            System.out.println("1"+page);
//        }else {
//            page=JSONUtil.toBean(jsonUserPage, new TypeReference<IPage<User>>() {
//            },false);
//
//            System.out.println("2"+page);
//        }

        return Result.success(userService.page(userIPage, userQueryWrapper));

    }


    //导出接口
    @GetMapping("/export")
    public  void export(HttpServletResponse response) throws  Exception{
        List<User> users = userService .list();

        //在内存操作，写入浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        writer.addHeaderAlias("username","用户名");
        writer.addHeaderAlias("password","密码");
        writer.addHeaderAlias("nickname","昵称");
        writer.addHeaderAlias("email","邮箱");
        writer.addHeaderAlias("phone","电话");
        writer.addHeaderAlias("address","地址");
        writer.addHeaderAlias("creatTime","创建时间");
        writer.addHeaderAlias("avatarUrl","头像");

        //一次性写users内的对象到excel，使用默认样式，强制输出标题
        writer .write(users,true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName= URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    //导入接口
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws  Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            user.setAvatarUrl(row.get(6).toString());
            users.add(user);
        }
//        users.forEach(s-> {
//            userService.insterUser(s);
//        });
        userService.saveBatch(users);
        return Result.success(true);
    }


    //登录
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO){
        UserDTO userDTO1=iUserService.login(userDTO);
        return Result.success(userDTO1);
    }

    //注册
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        User userDTO1 =iUserService.register(userDTO);
        return Result.success(userDTO1);
    }

    //获取用户信息
    @GetMapping("/username/{username}")
    public Result username(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        String jsonstr = stringRedisTemplate.opsForValue().get(Constans.USER_PERSON);
        User one;
        if (StrUtil.isBlank(jsonstr)) {
            one = userService.getOne(queryWrapper);
            stringRedisTemplate.opsForValue().set(Constans.USER_PERSON, JSONUtil.toJsonStr(one), 1, TimeUnit.MINUTES);
        } else {
            one = JSONUtil.toBean(jsonstr, new TypeReference<User>() {
            }, true);
        }

        return Result.success(one);
    }

    //查询权限为老师的集合
    @GetMapping("/teachers")
    public Result getTeachers() {
        return Result.success(userService.getTeacher("ROLE_TEACHER"));
    }

    //增删改，删除redis缓存
    private void flushredis(String key) {
        stringRedisTemplate.delete(key);
    }


}
